import 'package:flutter/material.dart';
import 'package:fsharing/core/models/search.dart';
import 'package:fsharing/core/models/store_product_query.dart';
import 'package:fsharing/core/viewmodels/pages/home/search_model.dart';
import 'package:fsharing/core/viewmodels/pages/home/search_product_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/widgets/product_item.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchProductPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<SearchModel, SearchProductModel>(
      create: (context) => SearchProductModel(Provider.of(context, listen: false)),
      update: (context, searchModel, model) => model..keyword = searchModel.keyword,
      child: Consumer<SearchProductModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget();
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    SearchProductModel model = Provider.of(context, listen: false);
    List<Product> list = model.list;
    Search search = model.search;
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.builder(
        itemBuilder: (context, index) {
          return ProductItem(
            product: list[index],
          );
        },
        itemCount: list.length,
      ),
      enablePullDown: false,
      enablePullUp: search.models.content.length == 10,
      onLoading: () => _onLoadData(context),
    );
  }

  void _onLoadData(BuildContext context) async {
    SearchProductModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}
